/* components */
import SimilarQuestionDialog from "@gpt/views/question/similar-question-dialog";
/* enum */
import ComponentNameEnum from "@model/enum/ComponentNameEnum";
/* vue */
import { defineComponent, PropType } from "vue";
/* types */
import { SettingGPTQuestionItemType } from "@src/modules/setting/gpt/types";
/* hooks */
import { 
  useFetchSettingGPTGenerateSimilarQuestions, 
  useFetchSettingGPTQuestion, 
  useFetchSettingGPTRobotList 
} from "@src/modules/setting/gpt/hooks";
/* utils */
import { getRootWindowInitData } from "@src/util/window";
import { isEmpty, isFalsy } from "@src/util/type";
import { message } from "@src/util/message";
import { cloneDeep } from "lodash";

type SimilarQuestionDialogComponent = InstanceType<typeof SimilarQuestionDialog>

export default defineComponent({
  name: ComponentNameEnum.SettingGPTQuestionEditView,
  props: {
    isAdd: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    value: {
      type: Object as PropType<SettingGPTQuestionItemType>,
      default: () => ({} as SettingGPTQuestionItemType)
    }
  },
  setup(props, { emit }) {
    
    const { fetchGptRobotList, gptRobotList } = useFetchSettingGPTRobotList()
    const { 
      fetchGenerateSimilarQuestions, 
      similarQuestions, 
      loading: fetchGenerateSimilarQuestionsLoading
    } = useFetchSettingGPTGenerateSimilarQuestions()
    
    const { 
      loading: fetchSettingGPTQuestionLoading,
      fetchQuestion,
      question
    } = useFetchSettingGPTQuestion()
    
    return {
      fetchGptRobotList,
      fetchGenerateSimilarQuestions,
      fetchQuestion,
      question,
      similarQuestions,
      gptRobotList,
      fetchGenerateSimilarQuestionsLoading,
      fetchSettingGPTQuestionLoading
    }
  },
  data() {
    return {
      insideValue: {} as SettingGPTQuestionItemType,
      newLine: '\n',
      similarQuestion: [] as string[],
      similarQuestionText: '',
      answer: '',
      applyRobotList: [] as string[],
      similarQuestionMaxLength: 20,
    }
  },
  computed: {
    attrs() {
      return {
        props: {
        },
        directives: [
          {
            name: 'loading',
            value: this.loading
          }
        ],
      }
    },
    loading(): boolean {
      return this.fetchSettingGPTQuestionLoading
    },
    questionText(): string {
      return this.insideValue.question
    },
    similarQuestionDialogComponent(): SimilarQuestionDialogComponent {
      return this.$refs.SimilarQuestionDialog as SimilarQuestionDialogComponent
    }
  },
  mounted() {
    
  },
  methods: {
    fetchGenerateSimilarQuestionsImpl() {
      
      if (isFalsy(this.isAdd)) {
        return
      }
      
      const rootWindowInitData = getRootWindowInitData()
      const tenantId = rootWindowInitData?.user?.tenantId
      
      const params = {
        question: this.questionText,
        tenantId: tenantId
      }
      
      this.fetchGenerateSimilarQuestions(params).then(() => {
        this.insideValue.similarQuestionList = this.similarQuestions
        this.initializeSimilarQuestion()
      })
      
    },
    getInsideValue(): SettingGPTQuestionItemType {
      return this.insideValue as SettingGPTQuestionItemType
    },
    initialize() {
      this.initAnswer()
      this.initializeSimilarQuestion()
    },
    async outsideInitialize(value: SettingGPTQuestionItemType) {
      
      if (value.id) {
        
        const isSuccess = await this.fetchQuestion({
          id: value.id
        })
        
        if (isSuccess && this.question) {
          value = {
            ...this.question,
            similarQuestionList: value?.similarQuestionList || []
          }
        }
        
      }
      
      this.insideValue = cloneDeep(value)
      
      // 如果相似问题列表为空，则初始化一个
      const similarQuestionList = this.insideValue.similarQuestionList || []
      if (isEmpty(similarQuestionList)) {
        this.insideValue.similarQuestionList = ['']
      }
      
    },
    outsideGetInsideValue(): SettingGPTQuestionItemType {
      return this.getInsideValue()
    },
    initializeForCreate() {
      this.initAnswer()
    },
    initializeForEdit() {
      this.initAnswer()
      this.initializeSimilarQuestion()
    },
    initApplyRobotList() {
      this.applyRobotList = this.insideValue.applyRobotList || []
    },
    initAnswer() {
      this.answer = this.insideValue.answer || ''
    },
    initializeSimilarQuestion() {
      const similarQuestionList = this.insideValue.similarQuestionList || []
      this.similarQuestionText = similarQuestionList.join(this.newLine)
    },
    onQuestionTextChangeHandler(value: string) {
      this.insideValue.question = value
    },
    onSimilarQuestionTextChangeHandler(value: string) {
      this.insideValue.similarQuestionList = value.split(this.newLine)
    },
    onApplyRobotListChangeHandler(value: string[]) {
      this.insideValue.applyRobotList = value
      this.initApplyRobotList()
    },
    onAnswerChangeHandler(value: string) {
      this.insideValue.answer = value
      this.initAnswer()
    },
    validate(): Promise<boolean> {
      
      if (isFalsy(this.insideValue.question)) {
        message.error('请输入问题')
        return Promise.resolve(false)
      }
      
      if (isFalsy(this.insideValue.answer)) {
        message.error('请输入答案')
        return Promise.resolve(false)
      }
      
      const FormRichtextComponent = this.$refs.FormRichtext as any
      const content = FormRichtextComponent.getContent()
      const maxLength = FormRichtextComponent.maxLength
      
      // content 去除所有的空格
      const contentWithoutSpace = content.replace(/\s/g, '')
      
      if (contentWithoutSpace.length > maxLength) {
        message.error(`答案最多输入${maxLength}个字符`)
        return Promise.resolve(false)
      }
      
      return Promise.resolve(true)
    },
    onAddSimilarQuestionHandler() {
      
      if (this.insideValue.similarQuestionList.length >= this.similarQuestionMaxLength) {
        message.warning(`最多添加${this.similarQuestionMaxLength}个相似问题`)
        return
      }
      
      this.insideValue.similarQuestionList.push('')
      
    },
    onSimilarQuestionDialogConfirmHandler(questions: string[]) {
      
      if (isEmpty(questions)) {
        return
      }
      
      const similarQuestionList = [
        ...this.insideValue.similarQuestionList,
        ...questions
      ].filter(Boolean)
      
      if (similarQuestionList.length > this.similarQuestionMaxLength) {
        message.warning(`最多添加${this.similarQuestionMaxLength}个相似问题，已达到添加上限`)
        return
      }
      
      this.insideValue.similarQuestionList = similarQuestionList
      
    },
    openGenerateSimilarQuestionsHandler() {
      
      if (isFalsy(this.questionText)) {
        message.error('请先输入问题')
        return
      }
      
      this.similarQuestionDialogComponent.open(this.questionText)
      
    },
    renderQuestionText() {
      return (
        <el-form-item
          label="问题"
          required
        >
          <el-input
            placeholder="请输入问题"
            clearable
            maxlength={50}
            value={ this.insideValue.question }
            onInput={ this.onQuestionTextChangeHandler }
          >
          </el-input>
        </el-form-item>
      )
    },
    renderSimilarQuestion() {
      // 相似问题列表
      const similarQuestionList = this.insideValue.similarQuestionList || []
      
      function onDeleteHandler(index: number) {
        
        if (similarQuestionList.length === 1) {
          message.warning('至少保留一个相似问题')
          return
        }
        
        similarQuestionList.splice(index, 1)
        
      }
      
      const onInputHandler = (index: number, value: string) => {
        this.$set(this.insideValue.similarQuestionList, index, value)
      }
      
      return (
        <div class="setting-gpt-question-edit-view-similar-question">
          <el-form-item
            label="相似问题"
          >
            
            {similarQuestionList.map((item, index) => {
              return (
                <div class="setting-gpt-question-edit-view-similar-question-item">
                  
                  <el-input
                    placeholder="请输入相似问题"
                    clearable
                    maxlength={50}
                    value={item}
                    onInput={(value: string) => onInputHandler(index, value)}
                  >
                  </el-input>
                  
                  <i 
                    class="iconfont icon-delete"
                    onClick={() => onDeleteHandler(index)}
                  >
                  </i>
                  
                </div>
              )
            })}
            
            <div class="setting-gpt-question-edit-view-similar-question-footer">
              <el-button 
                type="text"
                onClick={this.onAddSimilarQuestionHandler}
              >
                添加
              </el-button>
              <el-button
                type="text"
                onClick={this.openGenerateSimilarQuestionsHandler}
              >
                自动生成
              </el-button>
            </div>
            
          </el-form-item>
        </div>
      )
    },
    renderAnswer() {
      return (
        <el-form-item
          label="答案"
          required
        >
          <form-richtext
            ref="FormRichtext"
            maxLength={300}
            value={ this.insideValue.answer }
            onInput={ this.onAnswerChangeHandler }
          >
          </form-richtext>
        </el-form-item>
      )
    },
    renderApplyRobots() {
      return (
        <el-form-item
          label="应用至机器人"
          required
        >
          <el-select
            multiple
            value={ this.applyRobotList }
            onInput={ this.onApplyRobotListChangeHandler }
          >
            {this.gptRobotList.map((item) => {
              return (
                <el-option
                  label={ item.name }
                  value={ item.id }
                >
                </el-option>
              )
            })}
          </el-select>
        </el-form-item>
      )
    }
  },
  render() {
    return (
      <div class={ComponentNameEnum.SettingGPTQuestionEditView}>
        
        <el-form 
          ref="ElForm"
          label-position="top"
          { ...this.attrs }
        >
          
          { this.renderQuestionText() }
          { this.renderSimilarQuestion() }
          { this.renderAnswer() }
          
        </el-form>
        
        <SimilarQuestionDialog
          ref="SimilarQuestionDialog"
          question={this.questionText}
          onConfirm={this.onSimilarQuestionDialogConfirmHandler}
        >
        </SimilarQuestionDialog>
        
      </div>
    )
  }
});